package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BedServiceImpl implements BedService {

    @Autowired
    private BedMapper bedMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRoom(BedDto bedDto) {
        Bed bed = BeanUtil.toBean(bedDto, Bed.class);
        bed.setBedStatus(0);

        try {
            bedMapper.addRoom(bed);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.BED_INSERT_FAIL);
        }
        /**新建床位之后需要更新房间信息，这里面共有三张表即，房间表，房型表，床位表，通过传入的房间id找到
         * 房间信息再通过房间信息找到对应的房型表然后修改其床位数量
         */
        //1.这个我么要通过房间id找到房间id
        Long roomId = bed.getRoomId();
        //2.通过房间信息找到对应的房型表,修改床位数量
        bedMapper.addTypeBedNum(roomId);


    }

    @Override
    public BedVo getById(Long id) {
        return BeanUtil.toBean(bedMapper.getBedById(id), BedVo.class);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBed(BedDto bedDto) {
        Long count = bedMapper.countDiffBedNumber(bedDto.getId(), bedDto.getBedNumber());
        if (count > 0){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPEAT_BED_NUMBER);
        }

        Bed bed = BeanUtil.toBean(bedDto, Bed.class);
        bedMapper.updateBed(bed);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBedById(Long id) {
        // 首先获取到对应房间的bed实体类
        Bed bed = bedMapper.getBedById(id);
        if (bed == null) {
            throw new RuntimeException("000");
        }

        // 获取房间ID
        Long roomId = bed.getRoomId();

        // 删除床位
        bedMapper.deleteBedById(id);

        // 更新房间类型床位数量
        bedMapper.decrementRoomTypeBedNum(roomId);
    }

}

